var express = require('express');
var router = express.Router();
var utils = require('../../functions/utils');

router.get('/' , function(req,res)
{
	var html = "<form name='tmpForm' method='post' action='/articleList'></form>";
	html +=	"<script language=javascript>tmpForm.submit();</script>";

	res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
	res.end(html);

});

function makeSelectContentStateString(state)
{
		var str  = '';

		str += "<option  value='0' ";
		if(state == '0')
			str += "SELECTED ";
		str += ">ALL</option>";

		str += "<option  value='1' ";
		if(state == '1')
			str += "SELECTED ";
		str += ">PUBLIC</option>";

		str += "<option  value='2' ";
		if(state == '2')
			str += "SELECTED ";
		str += ">PRIVATE</option>";

		str += "<option  value='20' ";
		if(state == '20')
			str += "SELECTED ";
		str += ">DELETED</option>";

		return str;
}

function makeSelectBlockStateString(state)
{
		var str  = '';

		str += "<option  value='0' ";
		if(state == '0')
			str += "SELECTED ";
		str += ">ALL</option>";

		str += "<option  value='1' ";
		if(state == '1')
			str += "SELECTED ";
		str += ">OPEN</option>";

		str += "<option  value='2' ";
		if(state == '2')
			str += "SELECTED ";
		str += ">BLOCKED</option>";

		return str;
}

function makeSelectOrderTypeString(type)
{
		var str  = '';

		str += "<option  value='dateDesc' ";
		if(type == 'dateDesc')
			str += "SELECTED ";
		str += ">▼ DATE</option>";

		str += "<option  value='dateAsc' ";
		if(type == 'dateAsc')
			str += "SELECTED ";
		str += ">▲ DATE</option>";

		str += "<option  value='likeDesc' ";
		if(type == 'likeDesc')
			str += "SELECTED ";
		str += ">▼ LIKE COUNT</option>";

		str += "<option  value='likeAsc' ";
		if(type == 'likeAsc')
			str += "SELECTED ";
		str += ">▲ LIKE COUNT</option>";

		str += "<option  value='viewDesc' ";
		if(type == 'viewDesc')
			str += "SELECTED ";
		str += ">▼ VIEW COUNT</option>";

		str += "<option  value='viewAsc' ";
		if(type == 'viewAsc')
			str += "SELECTED ";
		str += ">▲ VIEW COUNT</option>";

		str += "<option  value='shareDesc' ";
		if(type == 'shareDesc')
			str += "SELECTED ";
		str += ">▼ SHARE COUNT</option>";

		str += "<option  value='shareAsc' ";
		if(type == 'shareAsc')
			str += "SELECTED ";
		str += ">▲ SHARE COUNT</option>";

		str += "<option  value='commentDesc' ";
		if(type == 'commentDesc')
			str += "SELECTED ";
		str += ">▼ COMMENT COUNT</option>";

		str += "<option  value='commentAsc' ";
		if(type == 'commentAsc')
			str += "SELECTED ";
		str += ">▲ COMMENT COUNT</option>";


		return str;
}

function makeSelectYearString(year)
{
		var str  = '';
		for(var i = 2014 ; i <= 2030 ; i ++)
		{
			if(year == i)
				str += "<option value='" + i + "' SELECTED>"+i+"</option>";
			else
				str += "<option value='" + i + "'>"+i+"</option>";
		}

		return str;
};

function makeSelectMonthString(mon)
{
		var str  = '';
		for(var i = 1 ; i <= 12 ; i ++)
		{
			if(mon == i)
				str += "<option value='" + utils.attachZero(i,2) + "' SELECTED>" + utils.attachZero(i,2) + "</option>";
			else
				str += "<option value='" + utils.attachZero(i,2) + "'>" + utils.attachZero(i,2) + "</option>";
		}

		return str;
};

function makeSelectDayString(day)
{
		var str  = '';
		for(var i = 1 ; i <= 31 ; i ++)
		{
			if(day == i)
				str += "<option value='" + utils.attachZero(i,2) + "' SELECTED>" + utils.attachZero(i,2) + "</option>";
			else
				str += "<option value='" + utils.attachZero(i,2) + "'>" + utils.attachZero(i,2) + "</option>";
		}

		return str;
};

function makeSelectHourString(hour)
{
		var str  = '';
		for(var i = 0 ; i <= 23 ; i ++)
		{
			if(hour == i)
				str += "<option value='" + utils.attachZero(i,2) + "' SELECTED>" + utils.attachZero(i,2) + "</option>";
			else
				str += "<option value='" + utils.attachZero(i,2) + "'>" + utils.attachZero(i,2) + "</option>";
		}

		return str;
};

function makeSelectMinSecString(ms)
{
		var str  = '';
		for(var i = 0 ; i <= 59 ; i ++)
		{
			if(ms == i)
				str += "<option value='" + utils.attachZero(i,2) + "' SELECTED>" + utils.attachZero(i,2) + "</option>";
			else
				str += "<option value='" + utils.attachZero(i,2) + "'>" + utils.attachZero(i,2) + "</option>";
		}

		return str;
};




router.post('/', function(req,res)
{
	var sessionKey = req.session.key;

	if(utils.isValidString(sessionKey))
	{
		var async = require('async');
		async.waterfall([
			function(cb)
			{
				utils.checkManagerSession(sessionKey , cb);
			}
			,function(result , cb) 
			{
				// 실패 - 로그인 페이지 
				if(result == 0)
				{
					utils.notifyManagerSessionExpired(req , res);
				}
				// 성공 - 실제 작업코드.
				else
				{	
				/////////////////////////////////////////////////////////////////////////////////////////////	
				/*
					Input parameters 

					articleCount
					page
					startPage
					endPage

					bodyKeyword
					nameKeyword
					loginIdKeyword

					orderType

					startYear
					startMonth
					startDay
					startHour
					startMin
					startSec
												   
					endYear
					endMonth
					endDay
					endHour
					endMin
					endSec



				*/

					var changeThumbArticleId = req.body.changeThumbArticleId;
					var changeThumbTime = req.body.changeThumbTime;



					// thumb time change일 경우
					require('async').series
					([
						function(cb)
						{
							if(utils.isValidString(changeThumbArticleId) && utils.isValidString(changeThumbTime))
							{
								console.log(changeThumbArticleId + ',' + changeThumbTime);
								var changeFunc = require('../../functions/changeThumbTime');
								changeFunc( changeThumbArticleId , changeThumbTime , cb);
							}
							else
							{
								cb();
							}
						}
						],function(err, results) 
						{
							var articleCount = req.body.articleCount;

							var page = req.body.page;
							var startPage = req.body.startPage;
							var endPage = req.body.endPage;

							var bodyKeyword = req.body.bodyKeyword;		
							var bodyKeyword2 = null;
							var nameKeyword = req.body.nameKeyword;		
							var nameKeyword2 = null;

							var tag = req.body.tag;		
							var tag2 = null;

							var effectId = req.body.effectId;

							var loginIdKeyword = req.body.loginIdKeyword;

							var contentState = req.body.contentState;
							var blockState = req.body.blockState;

							var viewCount = req.body.viewCount;
							var shareCount = req.body.shareCount;
							var likeCount = req.body.likeCount;
							var commentCount = req.body.commentCount;

							var orderType = req.body.orderType;
							if(!utils.isValidString(orderType))
								orderType = 'dateDesc';

							console.log('Article List : ' + orderType);

							var startYear = req.body.startYear;		
							var startMonth = req.body.startMonth;		
							var startDay = req.body.startDay;		
							var startHour = req.body.startHour;		
							var startMin = req.body.startMin;		
							var startSec = req.body.startSec;		

							var endYear = req.body.endYear;		
							var endMonth = req.body.endMonth;		
							var endDay = req.body.endDay;		
							var endHour = req.body.endHour;		
							var endMin = req.body.endMin;		
							var endSec = req.body.endSec;		

							var isBlock = req.body.isBlock;
							var blockArticleId = req.body.blockArticleId;



							if(!utils.isValidString(contentState))
								contentState=0;

							if(!utils.isValidString(blockState))
								blockState=0;

							// block하는게 있을 경우는 master 나머지는 replica
							var db = null;
							if(utils.isValidString(blockArticleId)) 
							{
								db = global.master_db;
								console.log('master');
							}
							else
							{
								blockArticleId = null;
								db = global.replica_db;
								console.log('replica');
							}




							// 안넘어오면 오늘날짜 첨부터 끝까지 
							if(!utils.isValidString(startYear))
							{
								var today = new Date();

								startYear = endYear = String(today.getFullYear());
								startMonth = endMonth = utils.attachZero(today.getMonth()+1 , 2); //January is 0!
								startDay = endDay = utils.attachZero(today.getDate());

								startHour = startMin = startSec = '00';
								endHour ='23';
								endMin = endSec = '59';

							}

							var startDate = startYear+'-'+startMonth+'-'+startDay+' '+startHour+':'+startMin+':'+startSec;
							var endDate = endYear+'-'+endMonth+'-'+endDay+' '+endHour+':'+endMin+':'+endSec;


							if(!utils.isValidString(bodyKeyword))
								bodyKeyword = null;
							else
							{
								bodyKeyword2 = bodyKeyword.replace(/[+\-*<>()~"@\\%?]/gi, ' '); // fulltext 검색에 넣으면 안되는 특수문자는 공백으로 처리  
								var list = bodyKeyword2.split(' ');	// 공백문자로 키워드 구분 
								bodyKeyword2 = '';
								for(var i = 0 ; i < list.length ; i ++)
								{
									if(list[i].length > 0)
										bodyKeyword2 += '+'+list[i]+'* ';	// 항목 필수 ,prefix 매칭
								}
							}


							if(!utils.isValidString(nameKeyword))
								nameKeyword = null;
							else
							{
								nameKeyword2 = nameKeyword.replace(/[+\-*<>()~"@\\%?]/gi, ' '); // fulltext 검색에 넣으면 안되는 특수문자는 공백으로 처리  
								var list = nameKeyword2.split(' ');	// 공백문자로 키워드 구분 
								nameKeyword2 = '';
								for(var i = 0 ; i < list.length ; i ++)
								{
									if(list[i].length > 0)
										nameKeyword2 += '+'+list[i]+'* ';	// 항목 필수 ,prefix 매칭
								}
							}


							if(!utils.isValidString(tag))
								tag = null;
							else
							{
								tag2 = tag.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, ''); // 특수문자 제거 
							}

							if(!utils.isValidString(loginIdKeyword))
								loginIdKeyword = null;
							if(!utils.isValidString(startDate))
								startDate = null;
							if(!utils.isValidString(endDate))
								endDate = null;

							if(!utils.isValidString(effectId))
								effectId = null;




							utils.debug(req.originalUrl);

							//utils.callLog(req);
							if(!utils.isValid(articleCount) || articleCount <= 0)
								articleCount = 10;

							if(!utils.isValid(viewCount) || viewCount <= 0)
								viewCount = 0;
							if(!utils.isValid(shareCount) || shareCount <= 0)
								shareCount = 0;
							if(!utils.isValid(likeCount) || likeCount <= 0)
								likeCount = 0;
							if(!utils.isValid(commentCount) || commentCount <= 0)
								commentCount = 0;


							if(!utils.isValid(page) || page <=0 )
								page=1;
							else
								page = Number(page);

							if(!utils.isValid(startPage) || startPage <=0)
								startPage = 1; 
							else
								startPage = Number(startPage);

							if(!utils.isValid(endPage) || endPage <=0)
								endPage = 10;
							else
								endPage = Number(endPage);


							var fs = require('fs');
							fs.readFile('./template/articleList' , function(error,data)
							{
								if(error)
								{
									throw err;
								}
								var html = String(data);


								db.connection.getConnection(function(err,connection)
								{
									if(err)
									{
										throw err;
									}

									var input_param = [articleCount, page, bodyKeyword2, nameKeyword2, tag2 , effectId ,  loginIdKeyword, contentState, blockState
														, viewCount , shareCount , likeCount , commentCount
														, isBlock,blockArticleId , orderType , startDate, endDate, global.config.storage.download.url];

									var sql = 'call manage_getArticleList(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';


									var query = connection.query(sql, input_param , function (err, rows) 
									{
										connection.release();
										if(err)
										{
											throw err;
										}

										
										var totalCount = rows[1][0].totalCount;
										var totalPage = rows[1][0].totalPage;

										// 귀찮다 개수대로 때려넣자.
										fs.readFile('./template/articleItem' , function(error,data)
										{
											if(error)
											{
												throw err;
											}

											var totalItem = '';
											var thumbWidth=120;
											var videoWidth=427;

											for(i = 0 ; i < rows[0].length ; i++)
											{
												var item = String(data);
												item = item.split("%ARTICLE_ID%").join(rows[0][i].ARTICLEID);
												
												if(!utils.isValidString(rows[0][i].MOVIEPATH))
													item = item.split("%MOVIE_PATH%").join('');
												else
													item = item.split("%MOVIE_PATH%").join(rows[0][i].MOVIEPATH);

												if(!utils.isValidString(rows[0][i].THUMBPATH))
													item = item.split("%THUMB_PATH%").join('');
												else
													item = item.split("%THUMB_PATH%").join(rows[0][i].THUMBPATH);

												item = item.split("%ENCRYPTED_ID%").join(rows[0][i].ENCRYPTEDARTICLEID);

												/// width , height 
												item = item.split("%THUMB_WIDTH%").join(thumbWidth); // thumbnail 가로는 고정 
												item = item.split("%THUMB_HEIGHT%").join(parseInt(thumbWidth*rows[0][i].HEIGHT/rows[0][i].WIDTH));

												item = item.split("%VIDEO_WIDTH%").join(videoWidth); // thumbnail 가로는 고정 
												item = item.split("%VIDEO_HEIGHT%").join(parseInt(videoWidth*rows[0][i].HEIGHT/rows[0][i].WIDTH));



												if(rows[0][i].BODY.length < 40)
												{
													for(l = rows[0][i].BODY.length;l<=40;l++)
														rows[0][i].BODY +='&nbsp;';
												}

												if(2 == rows[0][i].CONTENTSTATE)
													item = item.split("%STATUS%").join("<font color=BLUE>PRIVATE</font>");
												else if(20 == rows[0][i].CONTENTSTATE)
													item = item.split("%STATUS%").join("<font color=RED>DELETED</font>");
												else
													item = item.split("%STATUS%").join("PUBLIC");

												if(rows[0][i].BODY.length < 50)
												{
													for(l = rows[0][i].BODY.length;l<=50;l++)
														rows[0][i].BODY +='&nbsp';
												}

												if(20 != rows[0][i].CONTENTSTATE)
												{
													if(0 == rows[0][i].ISHIDE)
														item = item.split("%BLOCK_BUTTON%").join('<button onclick=javascript:block('+rows[0][i].ARTICLEID+')>BLOCK</button>');
													if(1 == rows[0][i].ISHIDE)
														item = item.split("%BLOCK_BUTTON%").join('<font color=RED>BLOCKED</font>&nbsp;&nbsp;<button onclick=javascript:unblock('+rows[0][i].ARTICLEID+')>OPEN</button>');
												}
												else
													item = item.split("%BLOCK_BUTTON%").join('');

												
												if(utils.isValidString(rows[0][i].BODY))
													item = item.split("%BODY%").join(rows[0][i].BODY);
												else
													item = item.split("%BODY%").join('');

												item = item.split("%REG_DATE%").join(rows[0][i].REGDATE);
												item = item.split("%VIEW_COUNT%").join(rows[0][i].VIEWCOUNT);
												item = item.split("%SHARE_COUNT%").join(rows[0][i].SHARECOUNT);
												item = item.split("%LIKE_COUNT%").join(rows[0][i].LIKECOUNT);
												item = item.split("%COMMENT_COUNT%").join(rows[0][i].COMMENTCOUNT);

												item = item.split("%THUMB_TIME%").join(rows[0][i].THUMBTIME);

												if(!utils.isValidString(rows[0][i].PROFILEPICPATH))
													item = item.split("%PROFILEPIC_PATH%").join(global.config.web.defaultProfileImageUrl);
												else
													item = item.split("%PROFILEPIC_PATH%").join(rows[0][i].PROFILEPICPATH);

												item = item.split("%NAME%").join(rows[0][i].NAME);
												item = item.split("%LOGIN_ID%").join(rows[0][i].LOGINID);

												totalItem += '\n' + item;
											}

											html = html.split("%CONTENTS%").join(totalItem); // 내용
											
											html = html.split("%ARTICLE_COUNT%").join(articleCount); // 한 화면에 보이는 개수

											bodyKeyword = !bodyKeyword ? '' : bodyKeyword;
											html = html.split("%BODY_KEYWORD%").join(bodyKeyword); 

											nameKeyword = !nameKeyword ? '' : nameKeyword;
											html = html.split("%NAME_KEYWORD%").join(nameKeyword); 

											loginIdKeyword = !loginIdKeyword ? '' : loginIdKeyword;
											html = html.split("%LOGINID_KEYWORD%").join(loginIdKeyword); 

											tag = !tag ? '' : tag;
											html = html.split("%TAG%").join(tag); 

											effectId = !effectId ? '' : effectId;
											html = html.split("%EFFECT_ID%").join(effectId); 

											startDate = !startDate ? '' : startDate;						
											html = html.split("%START_DATE%").join(startDate); 

											endDate = !endDate ? '' : endDate;
											html = html.split("%END_DATE%").join(endDate); 


											var pageNumbers='';
											if(totalCount == 0)
											{
												page=0;
												html = html.split("%NEXT_DISABLED%").join('DISABLED'); 
												html = html.split("%PREV_DISABLED%").join('DISABLED'); 

											}
											else
											{
												if(page ==1 )
													html = html.split("%NEXT_DISABLED%").join('DISABLED'); 
												else
													html = html.split("%NEXT_DISABLED%").join(''); 

												if(page == totalPage)
													html = html.split("%PREV_DISABLED%").join('DISABLED'); 
												else
													html = html.split("%PREV_DISABLED%").join(''); 

												//페이지넘버리스트를 넘을 경우
												if(startPage > page)
												{
													// 최근10개 페이지 리스트
													endPage = page;
													startPage = page-9;
													// 앞으로 10개가 되지 않으면 뒤로 늘린다.
													if(startPage <= 0 )
													{
														startPage = 1;
														endPage = 10;
													}
												}
												else if(endPage < page)
												{
													// 다음 10개 페이지 리스트 
													startPage = page;
													endPage = startPage + 9;
													// 뒤로 10개가 되지 않으면 앞으로 늘린다.
													if(endPage > totalPage )
													{
														endPage = totalPage;
														startPage = endPage - 9;
													}
												}
												else
												{
													if(startPage <= 0 ) startPage = 1;
													if(endPage > totalPage) endPage = totalPage;
												}

												for(var i=startPage;i<=endPage;i++)
												{
													if(i == page)
														pageNumbers +='&nbsp;<font color=red>' + i + '</font>';
													else
														pageNumbers +='&nbsp;<a href=javascript:movePage(' + i + ')>' + i + '</a>';
												}
											}

											html = html.split("%CURRENT_PAGE%").join(page); 
											html = html.split("%START_PAGE%").join(startPage); 
											html = html.split("%END_PAGE%").join(endPage); 
											html = html.split("%TOTAL_PAGE%").join(totalPage); 
											html = html.split("%TOTAL_COUNT%").join(totalCount); 


											html = html.split("%PAGE_NUMBERS%").join(pageNumbers); 

											var strSelect = makeSelectContentStateString(contentState);
											html = html.split("%CONTENT_STATE%").join(strSelect); 

											strSelect = makeSelectBlockStateString(blockState);
											html = html.split("%BLOCK_STATE%").join(strSelect); 

											html = html.split("%VIEW_COUNT%").join(viewCount); 
											html = html.split("%SHARE_COUNT%").join(shareCount); 
											html = html.split("%LIKE_COUNT%").join(likeCount); 
											html = html.split("%COMMENT_COUNT%").join(commentCount); 

											strSelect = makeSelectOrderTypeString(orderType);
											html = html.split("%ORDER_TYPE%").join(strSelect); 

											strSelect = makeSelectYearString(Number(startYear));
											html = html.split("%START_YEAR%").join(strSelect); 
											strSelect = makeSelectMonthString(Number(startMonth));
											html = html.split("%START_MONTH%").join(strSelect); 
											strSelect = makeSelectDayString(Number(startDay));
											html = html.split("%START_DAY%").join(strSelect); 
											strSelect = makeSelectHourString(Number(startHour));
											html = html.split("%START_HOUR%").join(strSelect); 
											strSelect = makeSelectMinSecString(Number(startMin));
											html = html.split("%START_MIN%").join(strSelect); 
											strSelect = makeSelectMinSecString(Number(startSec));
											html = html.split("%START_SEC%").join(strSelect); 


											strSelect = makeSelectYearString(Number(endYear));
											html = html.split("%END_YEAR%").join(strSelect); 
											strSelect = makeSelectMonthString(Number(endMonth));
											html = html.split("%END_MONTH%").join(strSelect); 
											strSelect = makeSelectDayString(Number(endDay));
											html = html.split("%END_DAY%").join(strSelect); 
											strSelect = makeSelectHourString(Number(endHour));
											html = html.split("%END_HOUR%").join(strSelect); 
											strSelect = makeSelectMinSecString(Number(endMin));
											html = html.split("%END_MIN%").join(strSelect); 
											strSelect = makeSelectMinSecString(Number(endSec));
											html = html.split("%END_SEC%").join(strSelect); 

											if(utils.isValidString(changeThumbArticleId) && utils.isValidString(changeThumbTime))
											{
												html += "<script language=javascript>alert('["+changeThumbArticleId+"] 의 thumbnail time 이 "+changeThumbTime+" 초로 변경되었습니다!');</script>";
											}



											res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
											res.end(html);

										}); // read file

									}); // query

								}); // getConnection

							}); // readfile
						} 

					);// series 
			//////////////////////////////////////////////////////////////////////////////////////////

				} // result==1 
			}
		]); //waterfall
	}
	// 암것도 없으면 loginPage
	else
	{
		utils.gotoManagerLoginPage(req , res);
	}
});

module.exports = router;